const defaultYear = "2025-01-01";

Component({
  externalClasses: ["t-class-title"],

  properties: {
    required: {
      type: Boolean,
      value: true,
    },
    title: {
      type: String,
      value: "时间范围",
    },
    value: {
      type: String,
      value: "", // e.g., '09:10-12:00'
    },
  },

  data: {
    pickerVisible: false,
    startTime: "",
    endTime: "",
    pickingMode: "start", // 'start' or 'end'
    pickerTitle: "选择开始时间",
    start: `${defaultYear} 00:00:00`,
  },

  observers: {
    value: function (val) {
      console.log("-----val---", val);
      if (val && val.includes("-")) {
        const [start, end] = val.split("-").map((s) => s.trim());
        this.setData({
          startTime: start,
          endTime: end,
        });
      } else {
        this.setData({ startTime: "", endTime: "" });
      }
    },
  },

  methods: {
    showPicker() {
      const { value } = this.properties;
      if (value && value.includes("-")) {
        const [start, end] = value.split("-").map((s) => s.trim());
        this.setData({ startTime: start, endTime: end });
      } else {
        this.setData({ startTime: "", endTime: "" });
      }

      this.setData({
        pickerVisible: true,
        pickingMode: "start",
        pickerTitle: "选择开始时间",
        start: `${defaultYear} 00:00:00`,
      });
    },

    hidePicker() {
      this.setData({ pickerVisible: false });
    },

    onConfirm(e) {
      const selectedTime = e.detail.value; // 'HH:mm'

      const toMinutes = (hhmm) => {
        const [h, m] = (hhmm || "00:00").split(":").map((x) => parseInt(x, 10));
        return h * 60 + m;
      };

      if (this.data.pickingMode === "start") {
        this.setData({
          startTime: selectedTime,
          pickerVisible: false,
        });
        setTimeout(() => {
          this.setData({
            pickingMode: "end",
            pickerTitle: "选择结束时间",
            pickerVisible: true,
            start: `${defaultYear} ${selectedTime}:00`,
          });
        }, 150);
      } else {
        const startMin = toMinutes(this.data.startTime);
        const endMin = toMinutes(selectedTime);
        if (endMin < startMin) {
          wx.showToast({ title: "结束时间必须不早于开始时间", icon: "none" });
          // Keep picker open in end mode
          this.setData({
            pickingMode: "end",
            pickerTitle: "选择结束时间",
            pickerVisible: true,
          });
          return;
        }
        const newRange = `${this.data.startTime}-${selectedTime}`;
        this.setData({ endTime: selectedTime, pickerVisible: false });
        this.triggerEvent("change", { value: newRange });
      }
    },
  },
});
